package com.docking.heylo.service.impl;

import com.docking.heylo.exception.GeneralException;
import com.docking.heylo.utils.HeyloMessageSource;
import io.rong.RongCloud;
import io.rong.methods.user.User;
import io.rong.models.Result;
import io.rong.models.response.TokenResult;
import io.rong.models.user.UserModel;
import org.junit.After;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component
@Configuration
public class RongCloudImServerImpl {

    @Autowired
    private HeyloMessageSource ms;


    private static final String APP_KEY = "p5tvi9dspei24";

    private static final String APP_SECRET = "pc1pCMnT6oX";

    /***
     * 默认头像
     */
    private static final String DEFAULT_AVATAR = "https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=125725620,749423492&fm=26&gp=0.jpg";


    /***
     * 注册容云帐号
     *
     * @param id
     * @param name
     * @param portrait
     * @return
     */
    public TokenResult register(String id,String name,String portrait){
        try {
            return  RongCloud.getInstance(APP_KEY, APP_SECRET).user.register(
                    buildModel(id, name, portrait)
            );
        } catch (Exception e) {
            throw new GeneralException(ms.getMessage("register.im.error"));
        }
    }

    /***
     * 修改容云帐号信息
     *
     * @param id
     * @param name
     * @param portrait
     * @return
     */
    public Integer update(String id,String name,String portrait){
        try {
            Result result = RongCloud.getInstance(APP_KEY, APP_SECRET).user.update(
                buildModel(id, name, portrait)
            );
            return result.getCode();
        } catch (Exception e) {
            throw new GeneralException(ms.getMessage("update.information.error"));
        }
    }


    private UserModel buildModel(String id, String name, String portrait){
        return new UserModel()
                .setId(id)
                .setName(StringUtils.isEmpty(name) ? String.format("畅友%s",id) : name)
                .setPortrait(StringUtils.isEmpty(portrait) ? DEFAULT_AVATAR : portrait)
                ;
    }


    public Integer updateAvatar(int userId, String avatar) {
        try {
            Result result = RongCloud.getInstance(APP_KEY, APP_SECRET).user.update(
                    new UserModel()
                            .setId(userId + "")
                            .setPortrait(StringUtils.isEmpty(avatar) ? DEFAULT_AVATAR : avatar)
            );
            return result.getCode();
        } catch (Exception e) {
            throw new GeneralException(ms.getMessage("update.information.error"));
        }
    }


}
